<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { ref, unref, reactive } from 'vue'
// import { ElTree, ElInput, ElDivider } from 'element-plus'
import { ElTree, ElSelect, ElOption, ElMessage } from 'element-plus'
import { getUserByIdApi, saveUserApi, updateUserApi, deleteUserByIdApi } from '@/api/department'
import type { DepartmentUserItem } from '@/api/department/types'
import { useTable } from '@/hooks/web/useTable'
import { Search } from '@/components/Search'
import Write from './components/Write.vue'
import WriteKey from './components/WriteKey.vue'
import Detail from './components/Detail.vue'
import { Dialog } from '@/components/Dialog'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import SoftKey3W from './components/Syunew3W.js'

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await getUserByIdApi({
      // id: unref(currentNodeKey),
      pageIndex: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list || [],
      total: res.data.total || 0
    }
  },
  fetchDelApi: async () => {
    const res = await deleteUserByIdApi({
      id: unref(ids)[0]
    })
    return res.code == '200'
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'name',
    label: t('userDemo.username')
  },
  {
    field: 'account',
    label: t('userDemo.account')
  },
  {
    field: 'password',
    label: '密码',
    search: {
      hidden: true
    },
    table: {
      width: 220,
      slots: {
        default: () => {
          return <div>*********</div>
        }
      }
    }
  },
  {
    field: 'pluginToken',
    label: '平安账户',
    search: {
      hidden: true
    }
  },
  {
    field: 'udnKey',
    label: 'U盾账号',
    search: {
      hidden: true
    }
  },
  {
    field: 'udnPass',
    label: 'U盾密码',
    search: {
      hidden: true
    }
  },
  {
    field: 'isUdn',
    label: '是否启用U盾校验',
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        options: [
          {
            label: '禁用',
            value: 0
          },
          {
            label: '启用',
            value: 1
          }
        ]
      },
      value: 1
    },
    table: {
      width: 220,
      slots: {
        default: (data: any) => {
          return <div>{data.row.isUdn == '1' ? '已启用' : '未启用'}</div>
        }
      }
    }
  },
  {
    field: 'type',
    label: '角色',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      width: 220,
      slots: {
        default: (data: any) => {
          return <div>{data.row.type == '1' ? '超级管理员' : '管理员'}</div>
        }
      }
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 240,
      slots: {
        default: (data: any) => {
          const row = data.row as DepartmentUserItem
          return (
            <>
              <BaseButton type="primary" onClick={() => action(row, 'edit')}>
                {t('exampleDemo.edit')}
              </BaseButton>
              <BaseButton type="danger" onClick={() => delData(row)}>
                {t('exampleDemo.del')}
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  currentPage.value = 1
  searchParams.value = params
  getList()
}

const treeEl = ref<typeof ElTree>()

// const currentNodeKey = ref('')
// const departmentList = ref<DepartmentItem[]>([])
// const fetchDepartment = async () => {
//   const res = await getDepartmentApi()
//   departmentList.value = res.data.list
//   currentNodeKey.value =
//     (res.data.list[0] && res.data.list[0]?.children && res.data.list[0].children[0].id) || ''
//   await nextTick()
//   unref(treeEl)?.setCurrentKey(currentNodeKey.value)
// }
// fetchDepartment()

// const currentDepartment = ref('')
// watch(
//   () => currentDepartment.value,
//   (val) => {
//     unref(treeEl)!.filter(val)
//   }
// )

// const currentChange = (data: DepartmentItem) => {
//   if (data.children) return
//   currentNodeKey.value = data.id
//   currentPage.value = 1
//   getList()
// }

// const filterNode = (value: string, data: DepartmentItem) => {
//   if (!value) return true
//   return data.departmentName.includes(value)
// }

const dialogVisible = ref(false)
const dialogVisible1 = ref(false)
const dialogTitle = ref('')

const currentRow = ref<DepartmentUserItem>()
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = ''
}

const delLoading = ref(false)
const ids = ref<string[]>([])

const delData = async (row?: DepartmentUserItem) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row
    ? [row.id]
    : elTableExpose?.getSelectionRows().map((v: DepartmentUserItem) => v.id) || []
  delLoading.value = true

  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const action = (row: DepartmentUserItem, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = { ...row, department: unref(treeEl)?.getCurrentNode() || {} }
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()
const writeKeyRef = ref<ComponentRef<typeof WriteKey>>()

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    try {
      const res = await (formData.id ? updateUserApi(formData) : saveUserApi(formData))
      if (res) {
        currentPage.value = 1
        getList()
      }
    } catch (error) {
      console.log(error)
    } finally {
      saveLoading.value = false
      dialogVisible.value = false
    }
  }
}

let mSoftKey3A

const saveKey = async () => {
  const writeKey = unref(writeKeyRef)
  const formData = await writeKey?.submit()
  if (formData) {
    saveLoading.value = true
    try {
      if (!formData.act || !formData.pwd) {
        ElMessage('内容不能为空！')
        return
      }

      var InString = formData.act
      var PwdString = formData.pwd

      var addr = 100 //要写入的地址
      mSoftKey3A = new SoftKey3W()
      var buf = new Uint8Array(1)
      var buf1 = new Uint8Array(1)
      var DevicePath
      DevicePath = await mSoftKey3A.FindPort(1) //'查找是否存在多把加密锁
      if (mSoftKey3A.GetLastError() == 0) {
        window.alert('系统上发现有2把及以上的加密锁，请只插入要进行的加密锁。')
        return false
      }
      DevicePath = await mSoftKey3A.FindPort(0) //'查找是否存在加密锁
      if (mSoftKey3A.GetLastError() != 0) {
        window.alert('未发现加密锁，请插入加密锁')
        return false
      }

      let lasterror = 0
      //写入字符串到地址101
      let OutLen = await mSoftKey3A.YWriteString(
        InString,
        addr + 1,
        'ffffffff',
        'ffffffff',
        DevicePath
      )
      buf[0] = OutLen
      //写入字符串的长度到地址100
      lasterror = await mSoftKey3A.YWriteEx(buf, addr, 1, 'ffffffff', 'ffffffff', DevicePath)

      //写入密码字符串到地址101
      let OutLen1 = await mSoftKey3A.YWriteString(
        PwdString,
        addr + 1 + InString.length + 1 + 1,
        'ffffffff',
        'ffffffff',
        DevicePath
      )
      buf1[0] = OutLen1
      //写入字符串的长度到地址100
      lasterror = await mSoftKey3A.YWriteEx(
        buf1,
        addr + 1 + InString.length + 1,
        1,
        'ffffffff',
        'ffffffff',
        DevicePath
      )

      if (lasterror != 0) window.alert('写入字符串长度错误。错误码：')
      else window.alert('写入字符串成功')
    } catch (error) {
      console.log(error)
    } finally {
      saveLoading.value = false
      dialogVisible1.value = false
    }
  }
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <!-- <ContentWrap class="w-250px">
      <div class="flex justify-center items-center">
        <div class="flex-1">{{ t('userDemo.departmentList') }}</div>
        <ElInput
          v-model="currentDepartment"
          class="flex-[2]"
          :placeholder="t('userDemo.searchDepartment')"
          clearable
        />
      </div>
      <ElDivider />
      <ElTree
        ref="treeEl"
        :data="departmentList"
        default-expand-all
        :expand-on-click-node="false"
        node-key="id"
        :current-node-key="currentNodeKey"
        :props="{
          label: 'departmentName'
        }"
        :filter-node-method="filterNode"
        @current-change="currentChange"
      >
        <template #default="{ data }">
          <div
            :title="data.departmentName"
            class="whitespace-nowrap overflow-ellipsis overflow-hidden"
          >
            {{ data.departmentName }}
          </div>
        </template>
      </ElTree>
    </ContentWrap> -->
    <ContentWrap class="flex-[3] ml-20px">
      <Search
        :schema="allSchemas.searchSchema"
        @reset="setSearchParams"
        @search="setSearchParams"
      />

      <div class="mb-10px">
        <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
        <BaseButton type="danger" @click="dialogVisible1 = true">U盾密钥写入</BaseButton>
        <!-- <BaseButton :loading="delLoading" type="danger" @click="delData()">
          {{ t('exampleDemo.del') }}
        </BaseButton> -->
      </div>
      <Table
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
        :pagination="{
          total
        }"
      />
    </ContentWrap>

    <Dialog v-model="dialogVisible1" title="U盾密钥写入">
      <WriteKey
        ref="writeKeyRef"
        :form-schema="[
          { component: 'Input', field: 'act', label: '账号' },
          { component: 'Input', field: 'pwd', label: '密码' }
        ]"
      />
      <template #footer>
        <BaseButton type="primary" @click="saveKey" :loading="saveLoading">
          {{ t('exampleDemo.save') }}
        </BaseButton>
        <BaseButton @click="dialogVisible1 = false">{{ t('dialogDemo.close') }}</BaseButton>
      </template>
    </Dialog>

    <Dialog v-model="dialogVisible" :title="dialogTitle">
      <Write
        v-if="actionType !== 'detail'"
        ref="writeRef"
        :form-schema="allSchemas.formSchema"
        :current-row="currentRow"
      />

      <Detail
        v-if="actionType === 'detail'"
        :detail-schema="allSchemas.detailSchema"
        :current-row="currentRow"
      />

      <template #footer>
        <BaseButton
          v-if="actionType !== 'detail'"
          type="primary"
          :loading="saveLoading"
          @click="save"
        >
          {{ t('exampleDemo.save') }}
        </BaseButton>
        <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
      </template>
    </Dialog>
  </div>
</template>
